//
//  UIView+ZoomHit.m
//  coyote
//
//  Created by Huadong Zheng on 2020/4/2.
//  Copyright © 2020 sanyol.cn. All rights reserved.
//

#import "UIView+ZoomHit.h"
#import <objc/runtime.h>


static char const * UIView_ZoomHit_zoomHitPointChar = "UIView_ZoomHit_zoomHitPoint";
@implementation UIView (ZoomHit)
+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
         Class class = [self class];
        
        SEL originalSelector = @selector(pointInside:withEvent:);
        SEL swizzledSelector = @selector(ex_pointInside:withEvent:);
        
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        
        BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if (didAddMethod) {
            class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }

    });
   
    
}

-(void)setZoomHitPoint:(CGPoint)zoomHitPoint{
    objc_setAssociatedObject(self, &UIView_ZoomHit_zoomHitPointChar, [NSValue valueWithCGPoint:zoomHitPoint], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(CGPoint)zoomHitPoint{
    NSValue * value = objc_getAssociatedObject(self, &UIView_ZoomHit_zoomHitPointChar);
    return [value CGPointValue];
}


-(BOOL)ex_pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
    if (!CGPointEqualToPoint(self.zoomHitPoint, CGPointZero)) {
        CGRect bounds = self.bounds;
        bounds = CGRectInset(bounds, -self.zoomHitPoint.x, -self.zoomHitPoint.y);
        return CGRectContainsPoint(bounds, point);
    }else{
        return [self ex_pointInside:point withEvent:event];
    }
    

}
@end
